package com.pdstudio.carrecom.ui.fragment;

import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.support.v4.view.ViewPager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.app.AppContext;
import com.pdstudio.carrecom.bean.City;
import com.pdstudio.carrecom.bean.HomeInfo;
import com.pdstudio.carrecom.common.BaseFragment;
import com.pdstudio.carrecom.R;
import com.pdstudio.carrecom.logger.Logger;
import com.pdstudio.carrecom.tools.StringUtils;
import com.pdstudio.carrecom.tools.UIHelper;
import com.pdstudio.carrecom.ui.activity.ActivitySelectCitys;
import com.pdstudio.carrecom.ui.activity.buy.ActivityBuy;
import com.pdstudio.carrecom.ui.activity.myclub.ActivityMyClubMain;
import com.pdstudio.carrecom.ui.activity.owner.ActivityOwner;
import com.pdstudio.carrecom.ui.adapter.NewsAdapter;
import com.pdstudio.carrecom.ui.view.InfiniteIndicatorLayout;
import com.pdstudio.carrecom.ui.view.PageInfo;
import com.pdstudio.carrecom.ui.view.slideview.BaseSliderView.OnSliderClickListener;
import com.pdstudio.carrecom.ui.view.slideview.DefaultSliderView;

import com.pdstudio.carrecom.ui.view.slideview.BaseSliderView;

/**
 * 类: FragmentHome <br>
 * 描述: 首页 <br>
 * 作者: ws <br>
 * 时间: 2015-5-21 下午11:42:45
 */
public class FragmentHome extends BaseFragment implements OnClickListener,
		OnSliderClickListener {

	public static final String TAG = "FragmentHome";

	public static final int MSG_WHAT_WEATHER = 1;

	private LinearLayout mLayoutBuy;
	private LinearLayout mLayoutSell;
	private LinearLayout mLayoutClub;

	private HomeInfo mHomeInfo;

	private TextView mCity;// 城市
	private TextView mCartipt;// 适宜度
	private TextView mStatus;// 天气状态
	private TextView mTemp;// 温度

	private NewsAdapter mAdapter;

	private ImageView mImg;

	private ArrayList<PageInfo> viewInfos = new ArrayList<>();
	private InfiniteIndicatorLayout mAnimCircleIndicator;

	private LinearLayout mLayoutSelectCity;

	private int type = 1;
	private String mCityName = "北京";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		_view = inflater.inflate(R.layout.fragment_home, container, false);
		_context = getActivity();

		initView();

		return _view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getWeather();
	}

	@Override
	public void onPause() {
		super.onPause();
		mAnimCircleIndicator.stopAutoScroll();
	}

	@Override
	public void onResume() {
		super.onResume();
		mAnimCircleIndicator.startAutoScroll();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.id_layout_buy:
			Logger.i("我要买车");
			Intent intentbuy = new Intent(_context, ActivityBuy.class);
			startActivity(intentbuy);
			break;
		case R.id.id_layout_sell:
			Logger.i("我是车主");
			Intent intentowner = new Intent(_context, ActivityOwner.class);
			startActivity(intentowner);
			break;
		case R.id.id_layout_club:
			Intent intent = new Intent(_context, ActivityMyClubMain.class);
			startActivity(intent);
			break;
		case R.id.home_select_city:
			Intent intentCity = new Intent(_context, ActivitySelectCitys.class);
			startActivityForResult(intentCity, type);
			break;
		case R.id.home_adimg:
			UIHelper.showWebView(_context, "http://www.baidu.com", "促销资讯");
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			// UIHelper.ToastMessage(_context,
			// ((City)data.getExtras().get("city")).toString());
			if (data!= null) {
				mCityName = (((City) data.getExtras().get("city")).getCity());
				Logger.i(mCityName);
				getWeather();
			}
			break;

		}
	}

	private void initView() {

		mAnimCircleIndicator = (InfiniteIndicatorLayout) _view
				.findViewById(R.id.infinite_anim_circle);

		mLayoutBuy = (LinearLayout) _view.findViewById(R.id.id_layout_buy);
		mLayoutSell = (LinearLayout) _view.findViewById(R.id.id_layout_sell);
		mLayoutClub = (LinearLayout) _view.findViewById(R.id.id_layout_club);
		mLayoutSelectCity = (LinearLayout) _view
				.findViewById(R.id.home_select_city);

		mLayoutBuy.setOnClickListener(this);
		mLayoutSell.setOnClickListener(this);
		mLayoutClub.setOnClickListener(this);
		mLayoutSelectCity.setOnClickListener(this);

		mCity = (TextView) _view.findViewById(R.id.id_weather_city);
		mCartipt = (TextView) _view.findViewById(R.id.id_weather_cartipt);
		mStatus = (TextView) _view.findViewById(R.id.id_weather_status);
		mTemp = (TextView) _view.findViewById(R.id.id_weather_temp);

		mImg = (ImageView) _view.findViewById(R.id.home_adimg);
		mImg.setOnClickListener(this);

		mImg.setImageResource(R.drawable.benz15);
	}

	private void initListView() {
		// todo:暂时用product代替，实际上要使用news
		mAdapter = new NewsAdapter(getActivity(), mHomeInfo.product);
		// mListView.setAdapter(mAdapter);
	}

	/**
	 * 
	 * 方法: initImage <br>
	 * 描述: 轮播绑定url <br>
	 * 作者: ws <br>
	 * 时间: 2015-7-4 上午12:15:55
	 */
	private void initSliderImage() {

		viewInfos.clear();
		for (int i = 0; i < mHomeInfo.product.size(); i++) {
			if (mHomeInfo.product.get(i).url != null) {
				viewInfos.add(new PageInfo(mHomeInfo.product.get(i).content,
						mHomeInfo.product.get(i).url));
			}
		}

		animCircleIndicator(_view);

	}

	/**
	 * 
	 * 方法: 轮播动画 <br>
	 * 描述: TODO <br>
	 * 作者: ws <br>
	 * 时间: 2015-7-3 下午11:59:07
	 * 
	 * @param view
	 */
	private void animCircleIndicator(View view) {

		for (PageInfo name : viewInfos) {
			DefaultSliderView textSliderView = new DefaultSliderView(
					getActivity());
			textSliderView.image(name.getUrl())
					.setScaleType(BaseSliderView.ScaleType.Fit)
					.setOnSliderClickListener(this);
			textSliderView.getBundle().putString("extra", name.getData());
			mAnimCircleIndicator.addSlider(textSliderView);
		}
		mAnimCircleIndicator
				.setIndicatorPosition(InfiniteIndicatorLayout.IndicatorPosition.Center_Bottom);
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Logger.i(TAG, msg);
			switch (msg.what) {
			case MSG_WHAT_WEATHER:// 天气列表
				if (mHomeInfo != null) {
					if (mHomeInfo.weather != null) {
						mCity.setText(mHomeInfo.weather.getCity() == null ? ""
								: mHomeInfo.weather.getCity());
						mCartipt.setText(mHomeInfo.weather.getCartipt() == null ? ""
								: mHomeInfo.weather.getCartipt());
						mStatus.setText(mHomeInfo.weather.getZs() == null ? ""
								: mHomeInfo.weather.getZs());
						mTemp.setText(mHomeInfo.weather.getTemperature() == null ? ""
								: mHomeInfo.weather.getTemperature());

					}
				}

				initSliderImage();
				initListView();
				break;

			default:
				break;
			}
		}
	};

	/**
	 * 方法: getWeather <br>
	 * 描述: 获取天气情况 <br>
	 * 作者: ws <br>
	 * 时间: 2015-5-24 上午10:22:01
	 */
	private void getWeather() {
		try {
			HttpExecuteJson http = new HttpExecuteJson(_context,
					mGetWeatherListener);
			// TODO: 从保存城市地方拿数据
			String city = StringUtils.utf8Encode(mCityName);
			// String url =
			// ServiceHelper.InitPage+"/"+city+"?uid="+AppContext.getInstance().getUserId();
			String url = ServiceHelper.Weather + "/" + city + "?uid="
					+ AppContext.getInstance().getUserId() + "&size=30-60";

			Logger.i(url);
			http.post(url, null);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private HttpExecuteJson.httpReturnJson mGetWeatherListener = new HttpExecuteJson.httpReturnJson() {

		@Override
		public void onSuccess(String result) {
			Logger.json(result);
			HomeInfo resultInfo = null;
			try {
				resultInfo = new Gson().fromJson(result,
						new TypeToken<HomeInfo>() {
						}.getType());
				if ((resultInfo != null)
						&& (resultInfo.msg
								.equals(ServiceHelper.msg_code_sucess))) {
					// 原本在initview的代码放在这下面
					try {
						mHomeInfo = resultInfo;
						Logger.i("首页", mHomeInfo);
						Message msg = new Message();
						msg.obj = mHomeInfo;
						msg.what = MSG_WHAT_WEATHER;
						mHandler.sendMessage(msg);

					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int error, String msg) {

		}

		@Override
		public void onCancel() {

		}
	};

	@Override
	public void onSliderClick(BaseSliderView slider) {
		Logger.i("asdfasdfaf", slider.getBundle().getString("extra"));
		// UIHelper.openBrowser(getActivity(),
		// slider.getBundle().getString("extra"));
		UIHelper.showWebView(getActivity(),
				slider.getBundle().getString("extra"), "广告详情");

	}

	public class MyOnPageChangeListener implements
			ViewPager.OnPageChangeListener {

		@Override
		public void onPageSelected(int position) {

		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

}
